﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>班组设置</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <style>
        .search-container {
            background: #fff;
            padding: 20px;
            margin-bottom: 15px;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,.05);
        }

        .search-row {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .search-item {
            display: flex;
            align-items: center;
            margin-right: 40px;
            margin-bottom: 15px;
        }

        .search-label {
            width: 100px;
            text-align: right;
            margin-right: 15px;
            font-size: 16px;
            font-weight: 500;
        }

        .search-input {
            width: 220px;
            height: 42px;
            font-size: 15px;
        }

        .btn-container {
            background: #fff;
            padding: 20px;
            margin-bottom: 15px;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,.05);
        }

        .table-container {
            background: #fff;
            padding: 15px;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,.05);
        }

        .layui-table {
            margin: 0;
            font-size: 17px;
        }

            .layui-table th {
                background-color: #f8f9fa;
                font-weight: 600;
                height: 55px;
                font-size: 18px;
                padding: 15px;
            }

            .layui-table td {
                height: 60px;
                padding: 15px;
                vertical-align: middle;
                font-size: 16px;
            }

        .operation-btn {
            margin-right: 8px;
            padding: 8px 15px;
            font-size: 15px;
        }

        /* 放大按钮 */
        .layui-btn {
            height: 40px;
            line-height: 40px;
            padding: 0 20px;
            font-size: 15px;
        }

        .layui-btn-sm {
            height: 36px;
            line-height: 36px;
            padding: 0 18px;
            font-size: 14px;
        }

        .layui-btn-xs {
            height: 32px;
            line-height: 32px;
            padding: 0 12px;
            font-size: 13px;
        }

        /* 放大复选框 */
        input[type="checkbox"] {
            transform: scale(1.3);
            margin: 0 8px;
        }

        /* 放大选择框 */
        .layui-form-select {
            font-size: 15px;
        }

        .layui-form-select dl {
            font-size: 15px;
        }

        /* 增加页面整体间距 */
        .layui-container-fluid {
            padding: 20px !important;
        }

        .status-pending {
            color: #ff5722;
        }

        .status-processing {
            color: #2196f3;
        }

        .status-completed {
            color: #4caf50;
        }

        .status-approved {
            color: #607d8b;
        }
    </style>
</head>
<body class="layui-bg-gray">
    <div class="layui-container-fluid" style="padding: 15px;">
        <!-- 搜索条件区域 -->
        <div class="search-container">
            <div class="search-row">
                <div class="search-item">
                    <label class="search-label">班组类型</label>
                    <select id="processType" class="layui-input search-input">
                        <option value="">请选择班组类型</option>
                        <option value="来料检验">来料检验</option>
                        <option value="过程检验">过程检验</option>
                        <option value="成品检验">成品检验</option>
                        <option value="出货检验">出货检验</option>
                    </select>
                </div>
                <div class="search-item">
                    <label class="search-label">班组编号</label>
                    <input type="text" id="orderCode" class="layui-input search-input" placeholder="请输入班组编号">
                </div>
                <div class="search-item">
                    <label class="search-label">班组名称</label>
                    <input type="text" id="productCode" class="layui-input search-input" placeholder="请输入班组名称">
                </div>
            </div>
                <div class="search-item">
                    <button type="button" class="layui-btn" id="searchBtn">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="button" class="layui-btn layui-btn-primary" id="resetBtn">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                </div>
            </div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="btn-container">
            <button type="button" class="layui-btn layui-btn-sm" id="addBtn">
                <i class="layui-icon layui-icon-add-1"></i> 新增
            </button>
            <button type="button" class="layui-btn layui-btn-sm" id="editBtn">
                <i class="layui-icon layui-icon-edit"></i> 修改
            </button>
            <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" id="deleteBtn">
                <i class="layui-icon layui-icon-delete"></i> 删除
            </button>
        </div>

        <!-- 数据表格 -->
        <div class="table-container">
            <table class="layui-table" lay-size="sm">
                <thead>
                    <tr>
                        <th width="60">
                            <input type="checkbox" id="checkAll" lay-skin="primary">
                        </th>
                        <th width="200">班组单编号</th>
                        <th width="200">班组名称</th>
                        <th width="150">班组类型</th>
                        <th width="180">操作</th>
                    </tr>
                </thead>
                <tbody id="dataTable">
                    <!-- 数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>

        <!-- 分页区域 -->
        <div id="pagination" style="text-align: right; margin-top: 15px;"></div>

    <!-- 班组详情弹窗模板 -->
    <div id="teamDetailDialog" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="teamDetailForm">
            <div class="layui-form-item">
                <label class="layui-form-label">班组编号</label>
                <div class="layui-input-block">
                    <input type="text" name="teamNumber" class="layui-input" readonly>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">班组名称</label>
                <div class="layui-input-block">
                    <input type="text" name="teamName" class="layui-input" readonly>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">班组类型</label>
                <div class="layui-input-block">
                    <input type="text" name="teamType" class="layui-input" readonly>
                </div>
            </div>
            <!-- 项目组成员表格 -->
            <div class="layui-form-item">
                <label class="layui-form-label">项目组成员</label>
                <div class="layui-input-block">
                    <table class="layui-table" lay-size="sm">
                        <thead>
                            <tr>
                                <th>用户名</th>
                                <th>用户昵称</th>
                                <th>电话</th>
                            </tr>
                        </thead>
                        <tbody id="teamMembersList">
                        </tbody>
                    </table>
                    <div id="teamMembersPagination"></div>
                </div>
            </div>
        </form>
    </div>


    <!-- 工单选择弹出框 -->

    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
        layui.use(['table', 'layer', 'form', 'laypage'], function() {
            var table = layui.table,
                layer = layui.layer,
                form = layui.form,
                laypage = layui.laypage,
                $ = layui.$;

            // 页面初始化
            $(document).ready(function() {
                loadTeamSetData();
                bindEvents();
            });

            // 加载班组设置数据
            function loadTeamSetData(page = 1, limit = 10) {
                // 显示加载中
                layer.load(1);
                
                $.ajax({
                    url: '@Url.Action("GetTeamSets", "TeamSet")',
                    type: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        layer.closeAll('loading');
                        console.log('原始数据:', data);
                        
                        // 强制尝试渲染数据
                        try {
                            if (data) {
                                renderTable(data);
                                renderPagination(data.length || 0, page, limit);
                            } else {
                                renderTable([]);
                                layer.msg('暂无数据', {icon: 0});
                            }
                        } catch (error) {
                            console.error('渲染过程中出错:', error);
                            layer.msg('数据渲染失败', {icon: 2});
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.closeAll('loading');
                        console.error('请求失败:', error);
                        console.error('状态码:', xhr.status);
                        console.error('响应文本:', xhr.responseText);
                        layer.msg('网络请求失败', {icon: 2});
                    }
                });
            }

            // 渲染表格数据
            function renderTable(data) {
                console.log('开始渲染表格，数据:', data);
                var html = '';
                
                // 强制转换为数组形式处理
                var dataArray = [];
                if (data) {
                    if (Array.isArray(data)) {
                        dataArray = data;
                    } else if (typeof data === 'object') {
                        // 如果是对象，尝试转换为数组
                        if (data.length !== undefined) {
                            dataArray = Array.from(data);
                        } else {
                            dataArray = [data];
                        }
                    }
                }
                
                console.log('处理后的数组:', dataArray);
                console.log('数组长度:', dataArray.length);
                
                if (dataArray && dataArray.length > 0) {
                    dataArray.forEach(function(item, index) {
                        console.log('渲染项目 ' + index + ':', item);
                        html += '<tr>';
                        html += '<td><input type="checkbox" lay-skin="primary" data-id="' + (item.id || item.Id || index) + '"></td>';
                        html += '<td><a href="javascript:void(0);" class="team-number-link" data-id="' + (item.id || item.Id || index) + '">' + (item.teamNumber || item.TeamNumber || '未知') + '</a></td>';
                        html += '<td>' + (item.teamName || item.TeamName || '未知') + '</td>';
                        html += '<td>' + (item.teamType || item.TeamType || '未知') + '</td>';
                        html += '<td>';
                        html += '<button type="button" class="layui-btn layui-btn-xs operation-btn edit-btn" data-id="' + (item.id || item.Id || index) + '">编辑</button>';
                        html += '<button type="button" class="layui-btn layui-btn-danger layui-btn-xs operation-btn delete-btn" data-id="' + (item.id || item.Id || index) + '">删除</button>';
                        html += '</td>';
                        html += '</tr>';
                    });
                    console.log('生成的HTML:', html);
                } else {
                    console.log('无数据，显示空状态');
                    html = '<tr><td colspan="5" style="text-align: center; padding: 50px;">暂无数据</td></tr>';
                }
                $('#dataTable').html(html);
                console.log('表格渲染完成');
            }

            // 渲染分页
            function renderPagination(total, page, limit) {
                if (total <= limit) {
                    $('#pagination').html('');
                    return;
                }
                
                laypage.render({
                    elem: 'pagination',
                    count: total,
                    curr: page,
                    limit: limit,
                    limits: [10, 20, 30, 50],
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    jump: function(obj, first) {
                        if (!first) {
                            loadTeamSetData(obj.curr, obj.limit);
                        }
                    }
                });
            }

            // 绑定事件
            function bindEvents() {
                // 搜索按钮
                $('#searchBtn').on('click', function() {
                    performSearch();
                });

                // 重置按钮
                $('#resetBtn').on('click', function() {
                    $('#processType').val('');
                    $('#orderCode').val('');
                    $('#productCode').val('');
                    form.render('select');
                    loadTeamSetData();
                });

                // 新增按钮
                $('#addBtn').on('click', function() {
                    layer.open({
                        type: 2,
                        title: '新增班组设置',
                        shadeClose: true,
                        shade: 0.3,
                        maxmin: true,
                        area: ['600px', '500px'],
                        content: '/TeamSet/AddTeam'
                    });
                });

                // 修改按钮
                $('#editBtn').on('click', function() {
                    var checkedItems = $('tbody input[type="checkbox"]:checked');
                    if (checkedItems.length === 0) {
                        layer.msg('请选择要修改的记录', {icon: 0});
                        return;
                    }
                    if (checkedItems.length > 1) {
                        layer.msg('只能选择一条记录进行修改', {icon: 0});
                        return;
                    }
                    
                    var id = checkedItems.first().data('id');
                    editTeamSet(id);
                });

                // 批量删除按钮
                $('#deleteBtn').on('click', function() {
                    var checkedItems = $('tbody input[type="checkbox"]:checked');
                    if (checkedItems.length === 0) {
                        layer.msg('请选择要删除的记录', {icon: 0});
                        return;
                    }
                    
                    var ids = [];
                    checkedItems.each(function() {
                        ids.push($(this).data('id'));
                    });
                    
                    layer.confirm('确定要删除这' + ids.length + '条记录吗？', {
                        btn: ['确定', '取消']
                    }, function(index) {
                        batchDeleteTeamSets(ids);
                        layer.close(index);
                    });
                });

                // 全选/取消全选
                $('#checkAll').on('click', function() {
                    var isChecked = $(this).prop('checked');
                    $('tbody input[type="checkbox"]').prop('checked', isChecked);
                });

                // 班组编号点击事件
                $(document).on('click', '.team-number-link', function() {
                    var id = $(this).data('id');
                    showTeamDetail(id);
                });

                // 行内编辑按钮
                $(document).on('click', '.edit-btn', function() {
                    var id = $(this).data('id');
                    editTeamSet(id);
                });

                // 行内删除按钮
                $(document).on('click', '.delete-btn', function() {
                    var id = $(this).data('id');
                    deleteTeamSet(id);
                });
            }

            // 执行搜索
            function performSearch() {
                var processType = $('#processType').val();
                var orderCode = $('#orderCode').val();
                var productCode = $('#productCode').val();
                
                // 这里可以添加搜索逻辑，传递参数到后端
                layer.msg('搜索功能待实现', {icon: 1});
            }

            // 编辑班组设置
            function editTeamSet(id) {
                console.log('编辑班组，ID:', id);
                layer.open({
                    type: 2,
                    title: '修改班组设置',
                    shadeClose: true,
                    shade: 0.3,
                    maxmin: true,
                    area: ['600px', '500px'],
                    content: '/TeamSet/EditTeam?id=' + id,
                    success: function(layero, index) {
                        console.log('弹窗加载完成');
                    }
                });
            }

            // 删除班组设置
            function deleteTeamSet(id) {
                layer.confirm('确定要删除这条记录吗？', {
                    btn: ['确定', '取消']
                }, function(index) {
                    // 显示加载中
                    layer.load(1);
                    
                    $.ajax({
                        url: '/TeamSet/Delete',
                        type: 'POST',
                        data: { id: id },
                        dataType: 'json',
                        success: function(response) {
                            layer.closeAll('loading');
                            
                            if (response.success) {
                                layer.msg(response.message || '删除成功', {icon: 1}, function() {
                                    // 刷新表格数据
                                    loadTeamSetData();
                                });
                            } else {
                                layer.msg(response.message || '删除失败', {icon: 2});
                            }
                        },
                        error: function(xhr, status, error) {
                            layer.closeAll('loading');
                            console.error('删除请求失败:', error);
                            console.error('状态码:', xhr.status);
                            console.error('响应文本:', xhr.responseText);
                            layer.msg('网络请求失败', {icon: 2});
                        }
                    });
                    
                    layer.close(index);
                });
            }

            // 批量删除班组设置
            function batchDeleteTeamSets(ids) {
                if (!ids || ids.length === 0) {
                    layer.msg('没有选择要删除的记录', {icon: 0});
                    return;
                }
                
                // 显示加载中
                layer.load(1);
                
                // 依次删除每个班组
                var deletePromises = ids.map(function(id) {
                    return new Promise(function(resolve, reject) {
                        $.ajax({
                            url: '/TeamSet/Delete',
                            type: 'POST',
                            data: { id: id },
                            dataType: 'json',
                            success: function(response) {
                                if (response.success) {
                                    resolve(response);
                                } else {
                                    reject(response.message || '删除失败');
                                }
                            },
                            error: function(xhr, status, error) {
                                reject('网络请求失败: ' + error);
                            }
                        });
                    });
                });
                
                Promise.all(deletePromises)
                    .then(function(results) {
                        layer.closeAll('loading');
                        layer.msg('批量删除成功', {icon: 1}, function() {
                            // 刷新表格数据
                            loadTeamSetData();
                        });
                    })
                    .catch(function(error) {
                        layer.closeAll('loading');
                        console.error('批量删除失败:', error);
                        layer.msg('批量删除失败: ' + error, {icon: 2});
                        // 即使部分失败也刷新数据
                        loadTeamSetData();
                    });
            }

            // 显示班组详情
            function showTeamDetail(id) {
                layer.load(1);
                
                // 获取班组基本信息
                $.ajax({
                    url: '/TeamSet/GetTeamById',
                    type: 'GET',
                    data: { id: id },
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            var team = response.data;
                            
                            // 填充表单数据
                            form.val('teamDetailForm', {
                                'teamNumber': team.teamNumber || team.TeamNumber,
                                'teamName': team.teamName || team.TeamName,
                                'teamType': team.teamType || team.TeamType
                            });
                            
                            // 加载成员数据
                            loadTeamMembers(id);
                            
                            // 打开弹窗
                            layer.open({
                                type: 1,
                                title: '班组详情',
                                area: ['800px', '600px'],
                                content: $('#teamDetailDialog'),
                                success: function() {
                                    form.render();
                                }
                            });
                        } else {
                            layer.msg(response.message || '获取班组数据失败', {icon: 2});
                        }
                        layer.closeAll('loading');
                    },
                    error: function(xhr, status, error) {
                        console.error('获取班组数据失败:', error);
                        layer.closeAll('loading');
                        layer.msg('网络请求失败', {icon: 2});
                    }
                });
            }
            
            // 加载班组成员数据
            function loadTeamMembers(teamId, page = 1, limit = 10) {
                $.ajax({
                    url: '/TeamSet/GetTeamMembers',
                    type: 'GET',
                    data: {
                        teamId: teamId,
                        page: page,
                        limit: limit
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            var html = '';
                            if (response.data && response.data.length > 0) {
                                response.data.forEach(function(member) {
                                    html += '<tr>';
                                    html += '<td>' + (member.userName || '') + '</td>';
                                    html += '<td>' + (member.userNickName || '') + '</td>';
                                    html += '<td>' + (member.userPhone || '') + '</td>';
                                    html += '</tr>';
                                });
                            } else {
                                html = '<tr><td colspan="3" style="text-align: center;">暂无成员数据</td></tr>';
                            }
                            $('#teamMembersList').html(html);
                            
                            // 渲染分页
                            if (response.total > limit) {
                                laypage.render({
                                    elem: 'teamMembersPagination',
                                    count: response.total,
                                    curr: page,
                                    limit: limit,
                                    layout: ['count', 'prev', 'page', 'next'],
                                    jump: function(obj, first) {
                                        if (!first) {
                                            loadTeamMembers(teamId, obj.curr, obj.limit);
                                        }
                                    }
                                });
                            } else {
                                $('#teamMembersPagination').empty();
                            }
                        } else {
                            layer.msg(response.message || '获取成员数据失败', {icon: 2});
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('获取成员数据失败:', error);
                        layer.msg('网络请求失败', {icon: 2});
                    }
                });
            }

            // 全局刷新方法，供子页面调用
            window.refreshTeamSetData = function() {
                loadTeamSetData();
            };
        });
    </script>
</body>
</html>
